package org.orm.oop.core.mapping;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.orm.oop.common.CommonConstants;
import org.orm.oop.common.util.FileUtils;
import org.orm.oop.core.mapping.model.MappingXml;

import java.io.*;
import java.net.URL;

@Slf4j
public class FreemarkerAutoMappingXml {

    public void autoMappingXml(MappingXml mappingXml) {
        Writer out = null;
        try {
            URL config = this.getClass().getResource(FreemarkerConstants.ORM_TEMPLATE_PATH_DIR);
            URL mappingPath = this.getClass().getResource(FreemarkerConstants.ORM_MAPPING_PATH);

            FreemarkerConstants.CONFIGURATION.setDirectoryForTemplateLoading(new File(config.getFile()));
            Template template = FreemarkerConstants.CONFIGURATION.getTemplate(FreemarkerConstants.DEFAULT_ORM_TEMPLATE_NAME);

            String pathName = mappingPath.getFile() + "/" + mappingXml.getTable() + FreemarkerConstants.ORM_TEMPLATE_SUFFIX;
            File file = new File(pathName);
            FileUtils.tryDelete(file);
            file.createNewFile();

            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            template.process(mappingXml, out);
        } catch (IOException | TemplateException e) {
            if(log.isErrorEnabled()) {
                log.error(String.format(CommonConstants.ERROR_PREFIX + "autoMapping fail", e));
            }
            throw new RuntimeException();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                if(log.isErrorEnabled()) {
                    log.error(String.format(CommonConstants.ERROR_PREFIX + "writer close fail", e2));
                }
                throw new RuntimeException();
            }
        }
    }
}
